#!/bin/bash
#文件名： pkcs3.sh
#用途：PKCS3协议实验
if [ $# -lt 1 ];
then
    echo 用法：$0 选项
    exit 0
fi

base_dir=`cd $(dirname $0); pwd -P`
cur_dir=`pwd`

if [ ! -d ./num ];  #如果目录下没有num文件夹
then
    mkdir num;  #新建一个文件夹
fi
case $1 in  #选择参数
-i )    # 初始化p、g、x、y,在当前目录下生成
    pg=(`$base_dir/get_g_p|awk 'NR>1'|xargs`)
    echo P is ${pg[0]}
    echo ${pg[0]}>$cur_dir/num/p.txt
    echo g is ${pg[1]}
    echo ${pg[1]}>$cur_dir/num/g.txt
    xy=(`$base_dir/get_x_y ${pg[0]} ${pg[1]}|awk 'NR>1'|xargs`)
    echo X is ${xy[0]}
    echo ${xy[0]}>$cur_dir/num/X.txt
    echo Y is ${xy[1]}
    echo ${xy[1]}>$cur_dir/num/Y.txt
    exit 0;;
-x )    #已有g和P，获取x和y
    if [[ ! -e $cur_dir/num/p.txt ]] || [[ ! -e $cur_dir/num/g.txt ]];   #如果缺少大素数或者生成元
    then
        echo 缺少运算关键文件！
        exit 0;
    fi 
    P=`cat $cur_dir/num/p.txt`   #获取P
    g=`cat $cur_dir/num/g.txt`   #获取g
    xy=(`$base_dir/get_x_y $P $g|awk 'NR>1'|xargs`)
    echo X is ${xy[0]}
    echo ${xy[0]}>$cur_dir/num/X.txt
    echo Y is ${xy[1]}
    echo ${xy[1]}>$cur_dir/num/Y.txt
    exit 0;;
-k )    #计算k
    if [[ ! -e $cur_dir/num/p.txt ]] || [[ ! -e $cur_dir/num/X.txt ]] || [[ ! -e $cur_dir/num/Yb.txt ]];   #如果缺少大素数、X或者对方的Y
    then
        echo 缺少运算关键文件！
        exit 0;
    fi     
    P=`cat $cur_dir/num/p.txt`   #获取P
    X=`cat $cur_dir/num/X.txt`   #获取X
    Yb=`cat $cur_dir/num/Yb.txt` #获取Yb
    k=`$base_dir/get_k $X $Yb $P|awk 'NR>1'|xargs`  #计算K
    echo k is $k
    echo $k>$cur_dir/num/K.txt #输出k到文件中
    exit 0;;
-e )    #加密
    if [[ ! -e $cur_dir/num/K.txt ]];   #如果缺少K
    then
        echo 请先生成密钥！
        exit 0;
    fi     
    K=`cat $cur_dir/num/K.txt`
    echo `$base_dir/endecode -e $K $2`
    exit 0;;
-d )    #加密
    if [[ ! -e $cur_dir/num/K.txt ]];   #如果缺少K
    then
        echo 请先生成密钥！
        exit 0;
    fi
    K=`cat $cur_dir/num/K.txt`
    echo `$base_dir/endecode -d $K $2`
    exit 0;;
esac
